#pragma once
#include <vector>
#include <queue>
#include "Cond.hpp"
#include "Thread.hpp"
#include "Log.hpp"
using namespace ThreadModule;
using namespace LogModule;

namespace ThreadPoolModule
{
    static int gnum = 5;
    template <class T>
    class ThreadPool
    {
        ThreadPool(int num = gnum) : _num(gnum), _isruning(false), _sleep_num(0)
        {
            for (int i = 0; i < num; i++)
            {
                _threads.emplace_back([this]() {
                    HandlerTask();
                });
            }
        }
        void WakeUpAllThread()
        {
            MutexGuard mutexguard(&_mutex);
            if (_sleep_num)
                _cond.Broadcast();
            LOG(LogLevel::INFO) << "唤醒所有休眠线程";
        }
        void WakeUpOneThread()
        {
            _cond.Signal();
            LOG(LogLevel::INFO) << "唤醒一个休眠线程";
        }
        void Start()
        {
            if(_isruning)
                return;
            _isruning = true;
            for(auto &thread : _threads)
            {
                thread.Start();
                LOG(LogLevel::INFO) << "start new thread success: " << thread.GetName();
            }
        }
        //关闭拷贝和赋值
        ThreadPool(const ThreadPool<T>&) = delete;
        ThreadPool<T>& operator=(const ThreadPool<T>&) = delete; 

    public:
        //懒汉的单例模式
        static ThreadPool<T>* GetInstance()
        {
            if(inc == nullptr)
            {
                MutexGuard mutexguard(&_lock);
                LOG(LogLevel::DEBUG) << "获取单例....";
                if(inc == nullptr)
                {
                    LOG(LogLevel::DEBUG) << "首次使用单例, 创建之....";
                    inc = new ThreadPool<T>();
                    inc->Start();
                }
            }
            return inc;
        }

        void HandlerTask()
        {
            char name[128];
            pthread_getname_np(pthread_self(),name,sizeof(name));
            while(true)
            {
                T t;
                {
                    MutexGuard mutexguard(&_mutex);
                    // if(_taskq.empty() && _isruning)
                    while(_taskq.empty() && _isruning)//用while循环，防止虚假唤醒，或者其他线程抢先竞争任务，导致任务队列为空，但是有线程被唤醒
                    {
                        _sleep_num++;
                        _cond.Wait(_mutex);
                        _sleep_num--;
                    }
                    //只有这两种情况才会退出
                    if(!_isruning && _taskq.empty())
                    {
                        LOG(LogLevel::INFO) << name << " 退出了, 线程池退出&&任务队列为空";
                        break;
                    }
                    t = _taskq.front();
                    _taskq.pop();
                }
                t();
            }
        }
        bool Enqueue(const T& t)
        {
            if(_isruning)
            {
                MutexGuard mutexguard(&_mutex);
                _taskq.push(t);
                //if(_threads.size() == _sleep_num)
                    WakeUpOneThread();
                return true;
            }
            return false;
        }
        void Stop()
        {
            if(!_isruning)
                return;
            _isruning = false;
            WakeUpAllThread();
        }
        void Join()
        {
            for (auto &thread : _threads)
            {
                thread.Join();
            }
        }
        
        ~ThreadPool()
        {
        }

    private:
        std::vector<Thread> _threads;
        int _num;             // 线程池中线程的个数
        std::queue<T> _taskq; // 任务队列
        Cond _cond;
        Mutex _mutex;

        bool _isruning;
        int _sleep_num;

        static ThreadPool<T> *inc;
        static Mutex _lock;
    };
    template <class T>
    ThreadPool<T>* ThreadPool<T>::inc = nullptr;
    template <class T>
    Mutex ThreadPool<T>::_lock;
}
